package com.ruoyi.web.controller.system;

import com.ruoyi.business.domain.BalanceChange;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.SysDictDataService;
import com.ruoyi.system.service.SysPostService;
import com.ruoyi.system.service.SysRoleService;
import com.ruoyi.system.service.SysUserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysPostService postService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private SysDictDataService sysDictDataService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions(value = {"system:user:list", "business:base:list"}, logical = Logical.OR)
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        startPage();
        if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
            user.setPid(ShiroUtils.getUserId());
        }
        List<SysUser> list = userService.selectUserList(user);
        list.forEach(sysUser -> {
            if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
                sysUser.setKey(null);
            }
            sysUser.setRoles(roleService.selectRolesByUserId(sysUser.getUserId()).parallelStream().filter(SysRole::isFlag).collect(Collectors.toList()));
        });
        return getDataTable(list);
    }

    @Log(title = "用户管理-导出用户数据", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据", sysDictDataService.selectAll(SysUser.class));
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream(), sysDictDataService.selectAll(SysUser.class));
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.importTemplateExcel("用户数据", sysDictDataService.selectAll(SysUser.class));
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        // 管理员才有权限设置账户余额
        if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
            user.setBalance(null);
            user.setPid(ShiroUtils.getUserId());
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
            user.setBalance(null);
            user.setPid(null);
        }
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (Objects.equals(ShiroUtils.getUserId(), user.getUserId())) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            SysUser sysUser = new SysUser();
            sysUser.setUpdateBy(ShiroUtils.getLoginName());
            sysUser.setIds(Arrays.asList(Convert.toLongArray(ids)));
            return toAjax(userService.deleteUserByIds(sysUser));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理-状态修改", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:open")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        SysUser u = new SysUser(user.getUserId());
        u.setStatus(user.getStatus());
        u.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.changeStatus(u));
    }

    @GetMapping("balance/{userId}")
    public String balance(@PathVariable Long userId, ModelMap mmap) {
        mmap.put("userId", userId);
        return prefix + "/balance";
    }

    @RequiresPermissions("system:user:balanceChange")
    @PostMapping("/balanceList")
    @ResponseBody
    public TableDataInfo balanceList(BalanceChange balanceChange) {
        startPage();
        List<BalanceChange> list = userService.selectBalanceList(balanceChange);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:balanceExport")
    @PostMapping("/balanceExport")
    @ResponseBody
    public AjaxResult balanceExport(BalanceChange balanceChange) {
        List<BalanceChange> list = userService.selectBalanceList(balanceChange);
        ExcelUtil<BalanceChange> util = new ExcelUtil<>(BalanceChange.class);
        return util.exportExcel(list, "余额变动", sysDictDataService.selectAll(BalanceChange.class));
    }

    @GetMapping("goChangeBalance/{userId}")
    public String goChangeBalance(@PathVariable Long userId, ModelMap mmap) {
        mmap.put("balance", userService.selectUserById(userId).getBalance());
        mmap.put("userId", userId);
        return prefix + "/changeBalance";
    }

    @Log(title = "用户管理-余额修改", businessType = BusinessType.UPDATE)
    @RequiresRoles("admin")
    @PostMapping("changeBalance")
    @ResponseBody
    public AjaxResult changeBalance(SysUser user,
                                    @NotNull(message = "充值类型不能为空") Integer changeBalanceType,
                                    @NotNull(message = "充值金额不能为空") Double money) {
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.changeBalance(user, changeBalanceType, money));
    }
}